package com.harry.utility.excel.base;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.harry.utility.excel.ExcelHeader;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
public abstract class ExcelPortA implements ExcelPortI {

	private Collection<ExcelHeader> headers;

	private Collection<Map<String, Object>> datas;

	/**
	 * CSV转XLS
	 * 
	 * @author LIANHANLIN - May 4, 2018 - 8:39:06 PM
	 */
	public static void csv2xls(InputStream in, String inputEncoding, OutputStream out) {
		BufferedReader readTxt = null;
		HSSFWorkbook writeWorkbook = null;
		try {
			readTxt = new BufferedReader(new InputStreamReader(in, inputEncoding != null ? inputEncoding : "utf-8"));
			String inStr = "";
			// 目标文件
			writeWorkbook = new HSSFWorkbook();
			HSSFSheet targetSheet = writeWorkbook.createSheet();
			HSSFRow targetRow;
			HSSFCell targetCell;
			for (int rowIndex = 0; (inStr = readTxt.readLine()) != null; rowIndex++) { // 读取
				targetRow = targetSheet.createRow(rowIndex); // 创建新行
				String str[] = inStr.split(","); // 得到列值
				for (int i = 0; i < str.length; i++) {
					targetCell = targetRow.createCell(i); // 创建新列
					targetCell.setCellValue(str[i]); // 赋值
				}
			}
			writeWorkbook.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				readTxt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				writeWorkbook.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}